import App from './App'

// #ifndef VUE3

import Vue, {createSSRApp} from 'vue'
import VueCompositionAPI from '@vue/composition-api'

// import './uni.promisify.adaptor'
// 引入全局TuniaoUI
import TuniaoUI from 'tuniao-ui'
import store from './store'
import staticDict from '@/util/staticDict.js'
import imgUrl from '@/util/imgUrl.js'

import UniRouteGuards from 'uniapp-route-guards';

Vue.use(VueCompositionAPI);
Vue.use(UniRouteGuards);

const guard = new UniRouteGuards();
const WHILE_FROM_LIST = ['/pages/login/index']
const LOGIN_PATH = '/pages/login/index'
const INDEX_PATH = '/pages/index/index'
let userStatus = uni.getStorageSync('userInfo')

// 统一的全局前置守卫（同步判断，避免异步回调导致守卫失效）
guard.beforeEach((to, from, next) => {
    // 同步读取用户信息，确保守卫能立即做出放行/拦截决策
    try {
        userStatus = uni.getStorageSync('userInfo')
    } catch (e) {
        userStatus = null
    }

    const toUrl = (to && typeof to.url === 'string') ? to.url : ''
    const fromUrl = (from && typeof from.url === 'string') ? from.url : ''
    const toAction = to && to.action

    const isFromWhite = WHILE_FROM_LIST.includes(fromUrl)

    // 仅放行未登录可访问的页面：登录页、首页的 PageA(index=0)/PageE(index=4)
    const isLoginPage = toUrl.startsWith(LOGIN_PATH)
    const isIndexPage = toUrl.startsWith(INDEX_PATH)
    let indexParam = null
    if (isIndexPage) {
        const match = toUrl.match(/(?:\?|&)index=(\d+)/)
        indexParam = match ? Number(match[1]) : null
    }
    const isIndexWhitelisted = isIndexPage && (indexParam === 0 || indexParam === 4)

    // 从白名单来源且是返回操作，直接放行
    if (isFromWhite && toAction === 'navigateBack') {
        return next()
    }

    // 未登录：仅允许登录页与首页的 PageA/PageE，其它一律跳登录
    if (!userStatus) {
        if (isLoginPage || isIndexWhitelisted) {
            return next()
        }
        // 访问首页但未指定或不是白名单 tab，统一落到 index=0
        if (isIndexPage) {
            return next(`${INDEX_PATH}?index=0`)
        }
        return next(LOGIN_PATH)
    }

    // 其余情况放行
    next()
})



//全局常量
global.staticDict = staticDict;
global.imgUrl = imgUrl;

Vue.use(TuniaoUI)
Vue.config.productionTip = false

Vue.prototype.$onLaunched = new Promise(resolve => {
    Vue.prototype.$isResolve = resolve;
})

// 引入TuniaoUI提供的vuex简写方法
let vuexStore = require('@/store/$tn.mixin.js')
Vue.mixin(vuexStore)
App.mpType = 'app'
const app = new Vue({
    store,
    ...App
})
app.$mount()

// #endif
// #ifdef VUE3
export function createApp() {
    const app = createSSRApp(App)
    return {
        app
    }
}
// #endif